package com.shiro.demo3.config;

import com.shiro.demo3.entity.User;
import com.shiro.demo3.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 和数据库交互,查看用户有什么角色和权限
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 权限信息
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        // 获取用户信息
        String username = (String) principal.getPrimaryPrincipal();
        // 根据用户名查询该用户的角色和权限
        /**
         * 这是查询数据库逻辑
         */
        // 设置角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 权限,从数据库查询权限
        info.addStringPermission("user:test");
        info.addStringPermission("user:test2");
        // 角色,从数据库查询角色
        info.addRole("role_admin");
        return info;
    }
    /**
     * 认证信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = ((UsernamePasswordToken) token).getUsername();
        // 数据库查询账号
        User user = userService.findByUsername(username);
        if (user != null) {
            // 第三个参数设置盐
            // ByteSource byteSource = new SimpleByteSource(user.getSalt());
            // 或者
            // ByteSource.Util.bytes(user.getSalt());
            // 第一个参数可以是User对象,或者username字符串
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
            return info;
        }
        return null;
    }
}
